'''
Created on Jan 11, 2010

@author: Alex
'''

import pickle
import pygame

try:
	import Tkinter as tk
	import tkFileDialog
except:
	print ("Failed to import Tkinter")

from filemanager import FileManager
class FileSave(FileManager):
	'''
	represents a base grid
	'''


	def __init__(self, parent, boundArray, listArray):
		'''
		Constructor
		'''
		FileManager.__init__(self)
		self.parent = parent
		tk_root = tk.Tk()
		tk_root.withdraw()
		self.__save(boundArray, listArray)
	
	def __save(self, boundArray, listArray):
		'''
		Checks given filename for supported extensions
		'''
		self.boundArray = boundArray
		self.listArray = listArray
		self.filename = tkFileDialog.asksaveasfilename(defaultextension='.mpy', filetypes=[('supported', ('*.mpy', '*.png', '*.jpg', '*.bmp')), ('map files', '*.mpy'),('tileset', ('*.png', '*.jpg', '*.bmp'))])
		if self.filename.endswith(".mpy"):
			self.__save_map()
		elif self.filename.endswith(".png") or self.filename.endswith(".jpg") or self.filename.endswidth(".bmp"):
			self.__save_image()
		else:
			print ("Selected file not supported")
		
	def __save_map(self):
		'''
		Saves the made map into a map file ".mpy"
		'''
		if self.connect(self.filename, 'wb') == 0:
			print ("Error while saving file")
			return
		pickle.dump(60, self.pickle_open)
		pickle.dump(self.boundArray, self.pickle_open)
		for tiles in self.listArray:
			temp = tiles.toString()
			pickle.dump(temp, self.pickle_open)
		self.close_connection()
			
	def __save_image(self):
		'''
		Saves the made map into an image file ".png", ".jpg", ".bmp"
		'''
		save_width_max = 0
		save_height_max = 0
		save_width_min = 9999999999
		save_height_min = 9999999999
		
		for tiles in self.listArray:
			if tiles.get_X() > save_width_max:
				save_width_max = tiles.get_X()
			if tiles.get_X() < save_width_min:
				save_width_min = tiles.get_X()
				
			if tiles.get_Y() > save_height_max:
				save_height_max = tiles.get_Y()
			if tiles.get_Y() < save_height_min:
				save_height_min = tiles.get_Y()
		
		save_width_max = save_width_max + self.parent.rect_x - save_width_min
		save_height_max = save_height_max + self.parent.rect_y - save_height_min
		
		save_surface = pygame.Surface((save_width_max, save_height_max))
		
		for tiles in self.listArray:
			for clips in tiles.get_Surface():
				save_surface.blit(clips, (tiles.get_X() - save_width_min, tiles.get_Y() - save_height_min))
			
		pygame.image.save(save_surface, self.filename)
		
		